package com.gowants.pems.service;

import com.gowants.pems.mapper.EquipmentMaintainMapper;
import com.gowants.pems.mapper.EquipmentMapper;
import com.gowants.pems.model.*;
import com.gowants.pems.util.Const;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.QRCodeUtil;
import com.gowants.pems.util.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EquipmentService {

	@Autowired
	private EquipmentMapper mapper;

	@Autowired
	private SysDictService sysDictService;

	@Autowired
	private EquipmentMaintainMapper maintainMapper;

	@Autowired
	private ParamsService paramsService;

	/**
	 * 新增设备
	 *
	 * @return
	 */
	@Transactional(rollbackFor = { Exception.class })
	public int saveEquipment(Equipment equipment) throws Exception {
		int i = 0;
		equipment.setId(UUID.randomUUID().toString());
		String path = paramsService.getParamValueByNumber(Const.qrCode_path);
		String qrCodePath = "/" + UUID.randomUUID().toString() + ".jpg";
		QRCodeUtil.encode(equipment.getId(), "", path + qrCodePath, false);
		equipment.setQrcode(qrCodePath);
		i = mapper.insert(equipment);
		if (i > 0) {
			if (equipment.getListFile() != null && equipment.getListFile().size() > 0) {
				List<EquipmentFile> fileList = equipment.getListFile().stream().map(m -> {
					m.setId(UUID.randomUUID().toString());
					m.setPid(equipment.getId());
					m.setType(0);
					String suffix = m.getName().substring(m.getName().lastIndexOf(".") + 1, m.getName().length());
					if (isImage(suffix)) {
						m.setType(1);
					}
					if ("xlsx".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix)) {
						m.setType(2);
					}
					if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
						m.setType(3);
					}
					if ("pdf".equalsIgnoreCase(suffix)) {
						m.setType(4);
					}
					if (isVideo(suffix)) {
						m.setType(5);
					}
					return m;
				}).collect(Collectors.toList());
				if (fileList.size() > 0) {
					mapper.insertFile(fileList);
				}

			}
			if (1 != equipment.getCycle()) {
				SysDict dict = new SysDict();
				dict.setDictId(equipment.getCycle());
				dict.setGroupId("equipment_cycle");
				List<SysDict> sysDict = sysDictService.selectList(dict);
				String unit[] = null;
				if (sysDict.size() > 0) {
					unit = sysDict.get(0).getRemarks().split(",");
				}
				Calendar calendar = Calendar.getInstance();

				Date date = calendar.getTime(); // 第一次执行定时任务的时间
				date = this.addDay(date, Integer.parseInt(unit[0]), Integer.parseInt(unit[1]));

				EquipmentMaintain equipmentMaintain = new EquipmentMaintain();
				equipmentMaintain.setId(UUID.randomUUID().toString());
				equipmentMaintain.setEquipmentId(equipment.getId());
				equipmentMaintain.setState(0);
				equipmentMaintain.setCreateTime(equipment.getCreateTime());
				equipmentMaintain.setEndTime(date);
				maintainMapper.insert(equipmentMaintain);
			}
		}
		return i;
	}

	// 增加或减少天数
	public Date addDay(Date date, int num, int type) {
		Calendar startDT = Calendar.getInstance();
		startDT.setTime(date);
		switch (type) {
		case 1:
			break;
		case 2:
			startDT.add(Calendar.DATE, num);
			break;
		case 3:
			startDT.add(Calendar.MONTH, num);
			break;
		case 4:
			startDT.add(Calendar.YEAR, num);
			break;
		}
		return startDT.getTime();
	}

	/**
	 * 新增设备
	 *
	 * @return
	 */
	@Transactional(rollbackFor = { Exception.class })
	public int editEquipment(Equipment equipment) {
		int i = 0;
		i = mapper.update(equipment);
		if (equipment.getListFile() != null && equipment.getListFile().size() > 0) {
			List<EquipmentFile> fileList = equipment.getListFile().stream().map(m -> {
				m.setId(UUID.randomUUID().toString());
				m.setPid(equipment.getId());
				m.setType(0);
				String suffix = m.getName().substring(m.getName().lastIndexOf(".") + 1, m.getName().length() - 1);
				if (isImage(suffix)) {
					m.setType(1);
				}
				if ("xlsx".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix)) {
					m.setType(2);
				}
				if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
					m.setType(3);
				}
				if ("pdf".equalsIgnoreCase(suffix)) {
					m.setType(4);
				}
				if (isVideo(suffix)) {
					m.setType(5);
				}
				return m;
			}).collect(Collectors.toList());
			if (fileList.size() > 0) {
				mapper.insertFile(fileList);
			}
		}
		if (equipment.getCycle() != 1) {
//			Date date = maintainMapper.selectMaxEndTime(equipment.getId());
//			maintainMapper.deleteUnMaintain(equipment.getId());

			SysDict dict = new SysDict();
			dict.setDictId(equipment.getCycle());
			dict.setGroupId("equipment_cycle");
			List<SysDict> sysDict = sysDictService.selectList(dict);
			String unit[] = null;
			if (sysDict.size() > 0) {
				unit = sysDict.get(0).getRemarks().split(",");
			}
			List<EquipmentMaintain> em=maintainMapper.selectByEid(equipment.getId());
			if(em.size()>0) {
				if(em.size()==1) {
					//存在一个未保养的信息
					//修改本条信息
					Date date = equipment.getCreateTime();
					date = this.addDay(date, Integer.parseInt(unit[0]), Integer.parseInt(unit[1]));
					EquipmentMaintain em0=new EquipmentMaintain();
					em0.setId(em.get(0).getId());
					em0.setEndTime(date);
					maintainMapper.update(em0);
				}else {
					Date date = em.get(1).getOperationTime();
					date = this.addDay(date, Integer.parseInt(unit[0]), Integer.parseInt(unit[1]));
					EquipmentMaintain em0=new EquipmentMaintain();
					em0.setId(em.get(0).getId());
					em0.setEndTime(date);
					maintainMapper.update(em0);
				}

			}else {
				Date date = equipment.getCreateTime();
				date = this.addDay(date, Integer.parseInt(unit[0]), Integer.parseInt(unit[1]));
				EquipmentMaintain equipmentMaintain = new EquipmentMaintain();
				equipmentMaintain.setId(UUID.randomUUID().toString());
				equipmentMaintain.setEquipmentId(equipment.getId());
				equipmentMaintain.setState(0);
				equipmentMaintain.setCreateTime(equipment.getCreateTime());
				equipmentMaintain.setEndTime(date);
				maintainMapper.insert(equipmentMaintain);
			}
		}
		return i;
	}

	/**
	 * 设备删除
	 *
	 * @param id
	 * @return
	 */
	@Transactional(rollbackFor = { Exception.class })
	public int deleteEquipment(String id) {
		int i = 0;
		i = mapper.delete(id);
		List<EquipmentFile> list = mapper.selectFile(id);
		String path = paramsService.getParamValueByNumber(Const.equipment_file_path);
		for (EquipmentFile file : list) {
			String address = file.getAddress();
			File f = new File(path + address);
			if (f.exists()) {
				f.delete();
			}
		}
		mapper.deleteFileByPid(id);
		return i;
	}

	/**
	 * 删除 设备文件
	 *
	 * @param address
	 * @return
	 */
	public int deleteEquipmentFile(String address) {
		int i = 0;
		i = mapper.deleteFileByAddress(address);
		if (mapper.selectByAddress(address) == 0) {
			i = 1;
		}
		String path = paramsService.getParamValueByNumber(Const.equipment_file_path);
		File file = new File(path + address);
		if (file.exists()) {
			file.exists();
		}
		return i;
	}

	/**
	 * <文件上传>
	 *
	 * @param myFile 文件 pathConfig 文件保存根路径 isRelpaceFileName 是否更换文件名 isCreateDir
	 *               是否创建新文件夹 isRelpaceFileName true: 文件名_时间戳 isCreateDir true:
	 *               按当前时间创建文件夹
	 * @return
	 * @remake
	 */
	public String upload(MultipartFile myFile, String pathConfig, String relativePath, String mappingPath,
			boolean isRelpaceFileName, boolean isCreateDir) {
		String result = "";
		String fileName = UploadUtil.getFileName(myFile);
		try {
			// 设置文件全限定名
			String path = paramsService.getParamValueByNumber(pathConfig);
			// 是否更换文件名
			if (isRelpaceFileName) {
				// fileName.
				// String[] fNames = fileName.split("\\.");
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
				Random rand = new Random();
				int x = rand.nextInt(999);
				String fNames = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
				fileName = df.format(new Date()) + x + "." + fNames;
			}
			// 是否创建文件夹
			if (isCreateDir) {
				String dir = DateUtil.getDays();
				fileName = dir + "/" + fileName;
			}
			// 拼接保存文件的全限定名
			String filePath = "";
			if (StringUtils.isNotBlank(relativePath)) {
				filePath += ("/" + relativePath);
			}
			filePath += ("/" + fileName);
			UploadUtil.saveFileFromInputStream(myFile.getInputStream(), path + filePath);
			// result = filePath.replace(path, "");
			result = filePath;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * <上传文件校验大小及格式>
	 *
	 * @param
	 * @return -1 大小不符合规定 0 上传类型不符合规定 1 校验通过
	 * @remake create by GJR 2019/7/1 11:31
	 */
	public int uploadCheck(MultipartFile myFile, String fileType, String fileSize) {
		if (!uploadFileSizeCheck(myFile, fileSize)) {
			return -1;
		}

		if (!uploadFileTypeCheck(myFile, fileType)) {
			return 0;
		}

		return 1;
	}

	/**
	 * <上传文件校验>
	 *
	 * @param
	 * @return
	 * @remake
	 */
	public boolean uploadFileSizeCheck(MultipartFile myFile, String fileSize) {
		// 文件大小不符合规定
		String size = paramsService.getParamValueByNumber(fileSize);

		// 未定义视为没限制
		if (null == size || "".equals(size)) {
			return true;
		}

		// 字节单位比较，数据库配置单位是MB
		if (myFile.getSize() > Long.valueOf(size) * 1024 * 1024) {
			return false;
		}

		return true;
	}

	/**
	 * <文件格式校验>
	 *
	 * @param
	 * @return
	 * @remake
	 */
	public boolean uploadFileTypeCheck(MultipartFile myFile, String fileType) {

		// 图片格式不符合规定
		String fileName = UploadUtil.getFileName(myFile);

		// 格式正则配置
		String type = paramsService.getParamValueByNumber(fileType);

		// 未定义视为没限制
		if (null == type || "".equals(type)) {
			return true;
		}

		if (!fileName.matches(type)) {
			return false;
		}
		return true;

	}

	private Boolean isImage(String suffix) {
		boolean bool = false;
		List<String> format = new ArrayList<>();
		format.add("JPG");
		format.add("jpg");
		format.add("BMP");
		format.add("bmp");
		format.add("GIF");
		format.add("gif");
		format.add("WBMP");
		format.add("wbmp");
		format.add("PNG");
		format.add("png");
		format.add("JPEG");
		format.add("jpeg");
		if (format.contains(suffix)) {
			bool = true;
		}
		return bool;
	}

	private Boolean isVideo(String suffix) {
		boolean bool = false;
		List<String> format = new ArrayList<>();
		format.add("wmv");
		format.add("asf");
		format.add("asx");
		format.add("rm");
		format.add("rmvb");
		format.add("mp4");
		format.add("3gp");
		format.add("mov");
		format.add("m4v");
		format.add("avi");
		format.add("dat");
		format.add("mkv");
		format.add("flv");
		format.add("vob");
		if (format.contains(suffix.toLowerCase())) {
			bool = true;
		}
		return bool;
	}
}
